<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/1.4.1/html2canvas.esm.js"></script>
  </head>
  <body>
    <div id="capture" style="padding: 10px; background: #f5da55">
      <h4 style="color: #000">Hello world!</h4>
    </div>
  </body>
</html>
<script>
  html2canvas(document.querySelector("#capture")).then((canvas) => {
    document.body.appendChild(canvas);
  });
  function asyncImage(url) {
    const img = new Image();
    img.src = url;
    img.setAttribute("crossOrigin", "anonymous");
    return new Promise((resolve, reject) => {
      img.onload = () => resolve(img);
      img.onerror = reject;
    });
  }
  var shareContent = YourTargetElem;
  var width = shareContent.offsetWidth;
  var height = shareContent.offsetHeight;
  var canvas = document.createElement("canvas");
  var scale = 2 || window.devicePixelRatio; //也可以使用设备像素比

  canvas.width = width * scale;
  canvas.height = height * scale;
  canvas.getContext("2d").scale(scale, scale);

  var opts = {
    scale: scale,
    canvas: canvas,
    logging: true,
    width: width,
    height: height,
  };
  html2canvas(shareContent, opts).then(function (canvas) {
    var context = canvas.getContext("2d");

    var img = Canvas2Image.convertToImage(canvas, canvas.width, canvas.height);

    document.body.appendChild(img);
    $(img).css({
      width: canvas.width / 2 + "px",
      height: canvas.height / 2 + "px",
    });
  });
</script>
